﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VIA.Project.Domain.Command
{
    public class DataTrigger
    {
        private int _value = -1;
        public static readonly DataTrigger EmptyTrigger = new DataTrigger();
        public int Value
        {
            get => _value;
            set
            {
                int oldValue = _value;
                _value = value;
                if (IsRisingEdgeEnable && oldValue == 0 && _value >= 1)
                {
                    OnRisingEdge();
                }
                else if (IsFallingEdgeEnable && oldValue >= 1 && _value == 0)
                {
                    OnFallingEdge();
                }
                if (IsHighLevelEnable && _value >= 1)
                {
                    OnHighLevel();
                }
                else if (IsLowLevelEnable && _value == 0)
                {
                    OnLowLevel();
                }
            }
        }
        public bool IsRisingEdgeAutoFeedBack { get; set; }
        public bool IsFallingEdgeAutoFeedBack { get; set; }
        public bool IsRisingEdgeEnable { get; set; } = true;
        public bool IsFallingEdgeEnable { get; set; } = true;
        public bool IsHighLevelEnable { get; set; }
        public bool IsLowLevelEnable { get; set; }
        public string Address { get; set; }
        public string FeedBackAddress { get; set; }

        public event EventHandler<string> RisingEdge;
        public event EventHandler<string> FallingEdge;
        public event EventHandler<string> HighLevel;
        public event EventHandler<string> LowLevel;
        public DataTrigger() { }
        public DataTrigger(string address, string feedBackAddrss)
        {
            Address = address;
            FeedBackAddress = feedBackAddrss;
        }

        private void OnRisingEdge()
        {
            RisingEdge?.Invoke(this, string.Empty);
        }

        private void OnFallingEdge()
        {
            FallingEdge?.Invoke(this, string.Empty);
        }

        private void OnHighLevel()
        {
            HighLevel?.Invoke(this, string.Empty);
        }

        private void OnLowLevel()
        {
            LowLevel?.Invoke(this, string.Empty);
        }
    }
}
